package com.aabte.auth.account.resource.api;

import com.aabte.auth.account.domain.exception.AccountNotExistException;
import com.aabte.auth.account.resource.api.group.*;
import com.aabte.auth.account.resource.facade.GroupServiceFacade;
import com.aabte.auth.group.domain.exception.GroupNotExistException;
import com.aabte.auth.role.domain.exception.RoleNotExistException;
import com.aabte.commons.bean.BaseResponse;
import com.aabte.commons.errorcode.ResponseFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@Slf4j
@ControllerAdvice
@Validated
@RestController
public class GroupController implements GroupApi {

    @Resource
    private GroupServiceFacade groupServiceFacade;

    @Override
    public BaseResponse<String> create(@Valid CreateGroupCommand command) {
        return ResponseFactory.success(groupServiceFacade.create(command.getGroupName()));
    }

    @Override
    public BaseResponse<Boolean> delete(String groupId) {
        try {
            return ResponseFactory.success(groupServiceFacade.delete(groupId));
        } catch (GroupNotExistException e) {
            throw GroupCode.GROUP_NOT_EXIST.newException(e);
        }
    }

    @Override
    public BaseResponse<Page<GroupDTO>> groups(Integer pageNumber, Integer pageSize) {
        return ResponseFactory.success(groupServiceFacade.groups(pageNumber, pageSize));
    }

    @Override
    public BaseResponse<Boolean> addAccount(AddAccountCommand command) {
        try {
            groupServiceFacade.addAccount(command.getGroupId(), command.getAccountId());
        } catch (GroupNotExistException e) {
            throw GroupCode.GROUP_NOT_EXIST.newException(e);
        } catch (AccountNotExistException e) {
            throw AccountCode.ACCOUNT_NOT_EXIST.newException(e);
        }
        return ResponseFactory.success(true);
    }

    @Override
    public BaseResponse<Boolean> addRole(AddRoleCommand command) {
        try {
            groupServiceFacade.addRole(command.getGroupId(), command.getRoleId());
        } catch (GroupNotExistException e) {
            throw GroupCode.GROUP_NOT_EXIST.newException(e);
        } catch (RoleNotExistException e) {
            throw AccountCode.ACCOUNT_NOT_EXIST.newException(e);
        }
        return ResponseFactory.success(true);
    }


}
